package com.search.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.search.entity.Snacks;
import com.search.service.SnacksService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Slf4j
@Controller
public class IndexController {
    @Autowired
    private SnacksService snacksService;
    @GetMapping
    public String index() {
        return "index";
    }

    @PostMapping("/search")
    public String search(@RequestParam(defaultValue = "1", value = "pageNum") Integer pageNum, @RequestParam String query, Model model) {
        int size = 8;
        log.info("search的参数为:pageNum={},size={},query={}", pageNum, size, query);
        PageHelper.startPage(pageNum,size);
        PageInfo pageInfo = new PageInfo();
        List<Snacks> lists = snacksService.getSnacksByNameOrIntroduction(query);
        // System.out.println(page.getTotal()+"    "+page.getList().size());
        PageInfo<Snacks> page = new PageInfo<Snacks>(lists);
        log.info("搜索的结果集：page={}", page);
        model.addAttribute("page", page);
        model.addAttribute("query", query);
        model.addAttribute("totalElements", page.getTotal());
        return "search";
    }
}
